// /* eslint-disable indent */
import React, { useState, useRef, useEffect } from 'react';

import { useDispatch } from 'react-redux';
import { useActions, useProps, useDevice } from '@ray-js/panel-sdk';

import { View, Button, Text, router, hideMenuButton, showLoading, hideLoading } from '@ray-js/ray';
import { Dialog, NavBar, Tabs, Tab, ConfigProvider, ActionSheet } from '@ray-js/smart-ui';

import _ from 'lodash';
import { updateTimerList } from '@/redux/modules/scheduleStateSlice';
import { useSystemInfo } from '@/hooks/useSystemInfo';
import { useDpIdByCode } from '@/hooks/useDpIdByCode';

import Strings from '../i18n';
import Weeks from '../component/weeks';
import Note from '../component/note';
import Action from '../component/action';
import ActionSlider from '../component/actionSlider';

import Picker from '../component/picker';
import Slider from '@/components/Slider';
import Slider2 from '@/components/Slider2';
import SliderSingle from '@/components/SliderSingle';
// import Calendar from '../component/calendar';

import { addSchedule, updateSchedule, removeSchedule } from '../utils';
import { AddOrEditParams, TimerModel } from '../type';

import styles from './index.module.less';

export default function AddSchedule({ location }) {
  const [controlId, control2Id, percentID, percent2ID] = useDpIdByCode<string[]>([
    'control',
    'control_2',
    'percent_control',
    'percent_control_2',
  ]);

  const { query } = location;

  const isEdit = query?.isEdit === 'true';

  const { curtain_mode: curtainMode } = useProps();
  console.log(`🚀 ~ curtainMode:`, curtainMode);

  const currentInfo = JSON.parse(query?.currentInfo || '{}') as TimerModel;

  const { timerId, time: originTime, loops, aliasName, dps: originDps } = currentInfo;

  const getTime = () => {
    const now = new Date();
    const hour = now.getHours();
    const minute = now.getMinutes();

    if (isEdit) {
      const [hour, minute] = originTime.split(':');
      return {
        hour: +hour,
        minute: +minute,
      };
    }
    return {
      hour,
      minute,
    };
  };

  const getWeeks = () => {
    if (isEdit) {
      return loops.split('').map(Number);
    }
    return [0, 0, 0, 0, 0, 0, 0];
  };

  const getNote = () => {
    if (isEdit) {
      return aliasName;
    }
    return '';
  };

  const getDps = () => {
    console.log('🐫 ~ file: index.tsx:82 ~ originDps:', originDps, isEdit);

    if (isEdit) {
      return originDps;
    }

    if (curtainMode === 'same') {
      return {
        [percentID]: 50,
      };
    }

    if (curtainMode === 'single') {
      return {
        [percentID]: 50,
        [percent2ID]: 50,
      };
    }

    if (curtainMode === 'conflict') {
      return {
        [controlId]: 'open',
      };
    }

    return {};
  };

  const [weeks, setWeeks] = useState<number[]>(getWeeks);
  const [note, setNote] = useState<string>(getNote);
  const [time, setTime] = useState(getTime);
  const [dps, setDps] = useState<Record<string, any>>(getDps);

  const [curDayDate, setCurDayDate] = useState<any>(new Date(2024, 0, 15).getTime());

  const dispatch = useDispatch();

  const handlePickerChange = (value: { hour: number; minute: number }) => {
    setTime(value);
  };

  const handleWeeksChange = (value: any) => {
    setWeeks(value);
  };

  const handleNoteChange = (value: string) => {
    setNote(value);
  };

  const handleActionChange = (value: Record<string, any>) => {
    setDps(value);
  };

  useEffect(() => {
    hideMenuButton();
  }, []);

  const handleSave = async () => {
    const Api = isEdit ? updateSchedule : addSchedule;

    const { hour, minute } = time;

    const timeStr = `${_.padStart(`${hour}`, 2, '0')}:${_.padStart(`${minute}`, 2, '0')}`;
    console.log('🐫 ~ file: index.tsx:130 ~ dps:', dps);

    const params: AddOrEditParams = {
      time: timeStr,
      loops: weeks.join(''),
      aliasName: note,
      dps,
    };

    if (isEdit) {
      params.timerId = timerId;
    }
    showLoading();
    Api(params).then(res => {
      hideLoading();
      dispatch(updateTimerList(res));
      router.back();
    });
  };

  const onClickLeft = React.useCallback(event => {
    router.back();
  }, []);

  const renderModeaAtion = () => {
    if (curtainMode === 'same') {
      return (
        <View className={styles.card}>
          <View className={styles.textBox}>
            <View>
              <Text className={styles.postion}>{Strings.getLang('leftPosition')}</Text>
              <View className={styles.postionValue}>{dps[percentID]}%</View>
            </View>
            <View
              style={{
                textAlign: 'right',
              }}
            >
              <Text className={styles.postion}>{Strings.getLang('rightPosition')}</Text>
              <View className={styles.postionValue}>{dps[percentID]}%</View>
            </View>
          </View>
          <View
            className={styles.slider}
            style={{
              overflow: 'hidden',
            }}
          >
            <Slider
              control=""
              leftValue={dps[percentID]}
              rightValue={dps[percentID]}
              bindchangend={e => {
                console.log(e, ' e.detail.value?.percent,');
                setDps({
                  ...dps,
                  [percentID]: e.detail.value?.percent,
                });
              }}
              mode="same"
            />
          </View>
        </View>
      );
    }

    if (curtainMode === 'single') {
      return (
        <View className={styles.card}>
          <View className={styles.textBox}>
            <View>
              <Text className={styles.postion}>{Strings.getLang('leftPosition')}</Text>
              <View className={styles.postionValue}>{dps[percentID]}%</View>
            </View>
            <View
              style={{
                textAlign: 'right',
              }}
            >
              <Text className={styles.postion}>{Strings.getLang('rightPosition')}</Text>
              <View className={styles.postionValue}>{dps[percent2ID]}%</View>
            </View>
          </View>
          <View
            className={styles.slider}
            style={{
              overflow: 'hidden',
            }}
          >
            <SliderSingle
              control=""
              leftValue={dps[percentID]}
              rightValue={dps[percent2ID]}
              bindchangend={e => {
                console.log(e, ' e.detail.value?.percent,');
                const type = e.detail.value?.type;
                const percentValue = e.detail.value?.percent;
                setDps({
                  ...dps,
                  [type === 'left' ? percentID : percent2ID]: percentValue,
                });
              }}
              mode="single"
            />
          </View>
        </View>
      );
    }

    if (curtainMode === 'conflict') {
      return (
        <Action
          style={{ marginTop: 52, paddingInline: 30, borderRadius: 10 }}
          dps={dps}
          dpId={controlId}
          onChange={handleActionChange}
        />
      );
    }
    return null;
  };

  return (
    <View className={styles.view}>
      <NavBar
        title={isEdit ? Strings.getLang('editTimer') : Strings.getLang('addTimer')}
        leftArrow
        onClickLeft={onClickLeft}
        rightText={Strings.getLang('save')}
        onClickRight={handleSave}
        className="navBar"
        rightTextClass={styles.deleteStyle}
      />
      <Picker time={time} handlePickerChange={handlePickerChange} />

      <Weeks style={{ marginTop: 32 }} weeks={weeks} onChange={handleWeeksChange} />
      {renderModeaAtion()}

      <Dialog id="smart-dialog" />
    </View>
  );
}
